import Speech from "@/utils/speech";
import { onMounted, onUnmounted, ref } from "vue";

export default function useSpeech(onSend: (message: string) => void) {
  const audioPanel = ref<{ open: () => void; close: () => void }>();
  const popupText = ref("");

  const time = ref({
    timer: 0,
    count: 0
  });

  onMounted(() => {
    Speech.instance.on("radio", (e: string) => {
      if (e) {
        popupText.value += e;
      }
    });
  });
  onUnmounted(() => {
    Speech.instance.off("radio");
  });

  function timeout() {
    time.value.timer = setTimeout(() => {
      time.value.count += 1;
      timeout();
    }, 1000);
  }
  const start = (e: any) => {
    e.preventDefault();
    e.stopPropagation();
    if (Speech.instance.creating) {
      return;
    }
    audioPanel.value?.open();
    if (time.value.timer) {
      clearTimeout(time.value.timer);
    }
    Speech.instance.start();
    timeout();
  };
  const end = () => {
    if (time.value.timer) {
      clearTimeout(time.value.timer);
    }
    audioPanel.value?.close();
    if (time.value.count <= 1) {
      Speech.instance.stop();
      uni.showToast({
        title: "录音时间太短",
        icon: "none"
      });
    }
    const text = popupText.value.trim();
    if (!text) {
      Speech.instance.stop();
      uni.showToast({
        title: "没有听到你的声音呢",
        icon: "none"
      });
    }

    if (text) {
      onSend?.(text);
      popupText.value = "";
    }
    time.value.count = 0;
  };

  return { time, popupText, audioPanel, start, end };
}
